package com.zhida.chatservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhida.chatservice.entity.GroupMessage;
import com.zhida.chatservice.entity.UserMessage;
import com.zhida.chatservice.mapper.GroupMessageMapper;
import com.zhida.chatservice.mapper.UserMessageMapper;
import com.zhida.chatservice.mapper.WsGroupMapper;
import com.zhida.chatservice.service.WsService;
import com.zhida.chatservice.utils.MsgUtil;
import com.zhida.common.context.UserContext;
import com.zhida.common.entity.FileObject;
import com.zhida.common.entity.Result;
import com.zhida.common.entity.WsGroup;
import com.zhida.common.utils.FileUtil;
import com.zhida.common.utils.ObjectUtil;
import jakarta.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zhida.common.utils.RegexUtil.WS_OFFLINE_KEY;

/**
 * Create by zhh 2024/7/16 7:48
 */
@Service
public class WsServiceImpl extends ServiceImpl<WsGroupMapper,WsGroup> implements WsService{

    @Resource
    final WsGroupMapper wsGroupMapper;
    @Resource
    final RedisTemplate<String,String> redisTemplate;
    @Resource
    final StringRedisTemplate stringRedisTemplate;
    @Autowired
    private GroupMessageMapper groupMessageMapper;
    @Autowired
    private UserMessageMapper userMessageMapper;

    public WsServiceImpl(WsGroupMapper wsGroupMapper, RedisTemplate<String, String> redisTemplate, StringRedisTemplate stringRedisTemplate) {
        this.wsGroupMapper = wsGroupMapper;
        this.redisTemplate = redisTemplate;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public Result<?> userOnline(String username) {
        String userWsOnline = redisTemplate.opsForValue().get(WS_OFFLINE_KEY + username);
        if ("".equals(userWsOnline)){
            return Result.successMsg("用户不在线");
        }
        return Result.successMsg("用户在线");
    }

    @Override
    public Result<?> createGroup(WsGroup wsGroup, String username) {
        wsGroup.setGroupOwner(username);
        wsGroupMapper.insert(wsGroup);
        return Result.successMsg("创建成功");
    }

    @Override
    public Result<?> joinGroup(Integer groupId, String username) {
//        从数据库中获取join_awaiter字段，并拼接上username再重新存入数据库

        WsGroup selectResult = wsGroupMapper.selectOne(new QueryWrapper<WsGroup>().eq("group_id", groupId));
        if (selectResult!=null){
//          将username插入
            String awaiter = selectResult.getJoinAwaiter()==null?"":selectResult.getJoinAwaiter();
            if (awaiter.contains(username)){
                return Result.successMsg("等待群主通过");
            }
            selectResult.setJoinAwaiter( "#" + username + "," + awaiter);
        } else {
            return Result.error404("请输入有效的群号");
        }
//            将result写入数据库
        UpdateWrapper<WsGroup> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("join_awaiter",selectResult.getJoinAwaiter()).eq("group_id", groupId);
        wsGroupMapper.update(new WsGroup(),updateWrapper);

        return Result.successMsg("已发送申请");
    }

    @Override
    public Result<?> getGroupsInfo() {
        String username = UserContext.getUser();
        return Result.success(wsGroupMapper.getGroupsAndInfo("%#" + username + ",%"));
    }

    @Override
    public Result<?> updateGroupInfo(HashMap<String,String> data) {
//        判断当前request用户是否为管理员或者群主
        String username = UserContext.getUser();
        QueryWrapper<WsGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq("group_id", data.get("group_id"))
                .nested(wrapper -> wrapper.eq("group_owner",UserContext.getUser()).or().like("group_admin","#" + username + ","));
        WsGroup wsGroup = wsGroupMapper.selectOne(queryWrapper);
        if (wsGroup != null){
            if (StringUtils.isNotBlank(data.get("base64"))){
                wsGroup.setGroupAvatar(data.get("base64"));
            }
            if (StringUtils.isNotBlank(data.get("group_name"))){
                wsGroup.setGroupName(data.get("group_name"));
            }
            wsGroupMapper.updateById(wsGroup);
            return Result.successMsg("更新完成");
        } else {
             wsGroup = wsGroupMapper.selectOne(new QueryWrapper<WsGroup>().eq("group_id", data.get("group_id")));
             if (wsGroup == null){
                 return Result.error404("资源不存在");
             }
        }
        return Result.error403("更新失败，权限不足。");
    }

    @Override
    public Result<?> getGroupMembers(String group_id) {
        QueryWrapper<WsGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", group_id).select("members,group_id");
        WsGroup wsGroup = wsGroupMapper.selectOne(queryWrapper);
        if (wsGroup != null){
            String membersStr = wsGroup.getMembers();
            String[] memberArr = membersStr.replace("#","").split(",");
            List<String> members = ObjectUtil.removeStringArrEmptyValue(memberArr);
            return Result.success(members);
        }
        return Result.error404("无成员信息");
    }

    @Override
    public Result<?> sendImages(List<MultipartFile> files, String jsonForm) {

//        判断files是否为空
        try {
            JsonNode jsonNode = ObjectUtil.JsonStr2Object(jsonForm);
            if (jsonNode == null){
                return Result.error("参数错误");
            }
            // 取当前时间戳
            String time = String.valueOf(System.currentTimeMillis());
            String from = UserContext.getUser();
            String to = jsonNode.has("to") ? jsonNode.get("to").asText() : null; // 如果"to"不存在，则返回null
            String msg = jsonNode.has("msg") ? jsonNode.get("msg").asText() : null; // 同上
            String group = jsonNode.has("group") ? jsonNode.get("group").asText() : null; // 同上
            if (StringUtils.isBlank(to) && StringUtils.isBlank(group)){
                return Result.error("参数错误，未指定消息接收者");
            }
            if (files.isEmpty()){
                if (StringUtils.isNotBlank(to)){
                    userMessageMapper.insert(new UserMessage(to,from,time,msg));
                }else {
                    groupMessageMapper.insert(new GroupMessage(group,from,time,msg));
                }
            }else {
                String type = "";
                List<Map<String,String>> fileNames = new ArrayList<>();
                if (StringUtils.isNotBlank(to)){
//                    私聊消息
                    type = "User";
                    fileNames = FileUtil.wsImageUpload(to, files, from, type);
                    userMessageMapper.insert(new UserMessage(to,from,time,ObjectUtil.Object2JsonStr(Map.of("msg",msg,"images",fileNames))));
                }else if(StringUtils.isNotBlank(group)) {
                    type = "Group";
//                    群聊消息
                    fileNames = FileUtil.wsImageUpload(group, files, from, type);
                    // 将信息插入数据库
                    groupMessageMapper.insert(new GroupMessage(group,from,time,ObjectUtil.Object2JsonStr(Map.of("msg",msg,"images",fileNames))));
                }
                return Result.success(fileNames);
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.error("参数异常");
    }
}
